<template>
  <div class="amap-container">
    <!-- 地图容器 -->
    <div ref="mapContainer" class="map"></div>

    <!-- 地图控制面板 -->
    <div v-if="showControls" class="map-controls">
      <button @click="zoomIn" class="control-btn" title="放大">➕</button>
      <button @click="zoomOut" class="control-btn" title="缩小">➖</button>
      <button @click="centerMap" class="control-btn" title="回到中心">📍</button>
      <button
        @click="toggleSatellite"
        class="control-btn"
        :title="isSatellite ? '普通地图' : '卫星地图'"
      >
        {{ isSatellite ? '🗺️' : '🛰️' }}
      </button>
      <!-- 热力图开关 -->
      <button
        @click="toggleHeatmap"
        class="control-btn"
        :class="{ active: showHeatmap }"
        :title="showHeatmap ? '关闭热力图' : '打开热力图'"
      >
        🔥
      </button>
      <!-- 地铁线路开关 -->
      <button
        @click="toggleSubwayList()"
        class="control-btn"
        :class="{ active: showSubway }"
        :title="showSubway ? '隐藏地铁线路' : '显示地铁线路'"
      >
        🚋
      </button>
      <!-- 公交线路开关 -->
      <button
        @click="toggleBusList()"
        class="control-btn"
        :class="{ active: showBus }"
        :title="showBus ? '隐藏公交线路' : '显示公交线路'"
      >
        🚌
      </button>
      <!-- 区域名称开关 -->
      <button
        @click="toggleDistricts()"
        class="control-btn"
        :class="{ active: showDistricts }"
        :title="showDistricts ? '隐藏区域名称' : '显示区域名称'"
      >
        📍
      </button>
      <!-- 打开关闭标点 -->
      <button
        @click="markersShow"
        class="control-btn"
        :class="{ active: isShowMarkers }"
        :title="isShowMarkers ? '隐藏标记点' : '显示标记点'"
      >
        🛣️
      </button>
      <!-- 打开路线 -->
      <button
        @click="toggleRoute()"
        class="control-btn"
        :class="{ active: showToggle }"
        :title="showToggle ? '隐藏路线' : '显示路线'"
      >
        🚇
      </button>
      <button
        @click="toggleLundu()"
        class="control-btn"
        :class="{ active: showLundu }"
        :title="showLundu ? '隐藏轮渡' : '显示轮渡'"
      >
        🚢
      </button>
      <button
        @click="searchAndDrawBinjiangBoundary()"
        class="control-btn"
        :class="{ active: BinjiangBoundary }"
        :title="BinjiangBoundary ? '隐藏滨江区' : '显示滨江区'"
      >
        🏙️
      </button>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <span>地图加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-overlay">
      <span>❌ 地图加载失败，请检查API密钥</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick, shallowRef } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

// 安全配置
window._AMapSecurityConfig = {
  securityJsCode: import.meta.env.VITE_AMAP_SECURITY_JS_CODE,
}

// 常量定义
const LINES = ['地铁1号线', '地铁4号线', '地铁5号线', '地铁6号线']
const BUS_LINES = ['1507M', '113']
const LUNDU_LINES = [
  [120.228456, 30.238765],
  [120.225678, 30.236543],
  [120.220123, 30.232109],
  [120.215876, 30.228765],
  [120.210123, 30.225109],
  [120.205123, 30.220109],
  [120.200123, 30.215109],
  [120.18123, 30.210109],
  [120.1749223, 30.208109],
]

// Props
const props = defineProps({
  center: {
    type: Array,
    default: () => [120.153576, 30.287459],
  },
  zoom: {
    type: Number,
    default: 13,
  },
  showControls: {
    type: Boolean,
    default: true,
  },
  markers: {
    type: Array,
    default: () => [],
  },
})

// Emits
const emit = defineEmits([
  'map-loaded',
  'marker-click',
  'map-click',
  'heatmap-toggle',
])

// Refs - 使用 shallowRef 减少响应式开销
const mapContainer = shallowRef(null)
const map = shallowRef(null)
const isSatellite = ref(false)
const markerInstances = shallowRef([])
const heatmap = shallowRef(null)
const showHeatmap = ref(false)
const loading = ref(true)
const error = ref(false)
const isShowMarkers = ref(false)
const showToggle = ref(false)
const satelliteLayer = shallowRef(null)
const lineSearch = shallowRef(null)
const myLine = shallowRef(null)
const lundulineSpolyline = shallowRef(null)
const showLundu = ref(false)
const showSubway = ref(false)
const showBus = ref(false)
const showDistricts = ref(false)
const BinjiangBoundary = ref(false)
const binjiangqupolygon = shallowRef(null)

// 使用 Map 替代对象，性能更好
const subwayLinesMap = shallowRef(new Map())
const busLinesMap = shallowRef(new Map())
const districtMarkers = shallowRef([])

// 线路颜色映射
const lineColorMap = {
  '地铁1号线': '#E12311',
  '地铁2号线': '#BF8157',
  '地铁3号线': '#037AC1',
  '地铁4号线': '#83C21F',
  '地铁5号线': '#E67818',
  '地铁6号线': '#291771',
  '地铁7号线': '#9267A6',
  '地铁8号线': '#808080',
  '地铁9号线': '#FFD700',
  '地铁10号线': '#00CED1',
  '地铁16号线': '#FF4500',
  '地铁19号线': '#fff',
  '1507M': '#0CB5BC',
  '113': '#FF4500',
}

// 防抖函数
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(this, args), delay)
  }
}

// 初始化地图
const initMap = async () => {
  // 防止重复初始化
  if (map.value) return

  try {
    loading.value = true
    error.value = false

    const AMap = await AMapLoader.load({
      key: import.meta.env.VITE_AMAP_KEY || '你的高德地图Key',
      version: '2.0',
      plugins: [
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.MapType',
        'AMap.HeatMap',
        'AMap.TileLayer',
        'AMap.LineSearch',
        'AMap.DistrictSearch',
        'AMap.Polygon',
      ],
    })

    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      viewMode: '2D',
      zoom: props.zoom,
      center: props.center,
      mapStyle: 'amap://styles/grey',
      zooms: [10, 18],
      pitch: 0,
      rotation: 0,
      animate: false,
      doubleClickZoom: false,
    })

    // 卫星图层
    satelliteLayer.value = new AMap.TileLayer.Satellite()
    satelliteLayer.value.hide()

    // 线路搜索
    lineSearch.value = new AMap.LineSearch({
      pageIndex: 1,
      pageSize: 10,
      city: '杭州市',
      citylimit: false,
      extensions: 'all',
    })

    // 热力图
    heatmap.value = new AMap.HeatMap(map.value, {
      radius: 25,
      opacity: [0, 0.8],
      gradient: {
        0.4: 'blue',
        0.6: 'cyan',
        0.7: 'lime',
        0.8: 'yellow',
        1.0: 'red',
      },
    })

    // 事件监听
    map.value.on('click', (e) => {
      emit('map-click', e.lnglat)
    })

    map.value.on('complete', () => {
      console.log('地图加载完成！')
      loading.value = false
      emit('map-loaded', map.value)
    })

  } catch (err) {
    console.error('高德地图加载失败:', err)
    loading.value = false
    error.value = true
  }
}

// 线路绘制函数
const createPolyline = (path, lineName, options = {}) => {
  const AMap = window.AMap
  if (!AMap) return null

  const defaultOptions = {
    strokeColor: lineColorMap[lineName] || '#3366FF',
    strokeOpacity: 0.8,
    strokeWeight: lineName.includes('地铁') ? 6 : 4,
    strokeStyle: 'solid',
    strokeDasharray: [0, 0],
  }

  const polyline = new AMap.Polyline({
    map: map.value,
    path: path,
    ...defaultOptions,
    ...options,
  })

  polyline.lineName = lineName
  return polyline
}

// 轮渡线路
const initLundu = () => {
  return createPolyline(LUNDU_LINES, '轮渡线路', {
    strokeColor: '#0CDDE4',
    strokeStyle: 'dashed',
    strokeDasharray: [10, 5],
  })
}

// 滨江区边界
const searchAndDrawBinjiangBoundary = debounce(async () => {
  BinjiangBoundary.value = !BinjiangBoundary.value
  const AMap = window.AMap
  if (!AMap || !map.value) return

  if (!BinjiangBoundary.value) {
    if (binjiangqupolygon.value) {
      map.value.remove(binjiangqupolygon.value)
      binjiangqupolygon.value = null
    }
    return
  }

  const districtSearch = new AMap.DistrictSearch({
    level: 'district',
    subdistrict: 0,
    city: '杭州',
    extensions: 'all',
  })

  districtSearch.search('滨江区', (status, result) => {
    if (status === 'complete') {
      const district = result.districtList[0]
      if (district && district.boundaries) {
        const boundary = district.boundaries[0].map(item => [item.lng, item.lat])
        
        binjiangqupolygon.value = new AMap.Polygon({
          path: boundary,
          strokeColor: '#B3EBAF',
          strokeWeight: 2,
          fillColor: '#B3EBAF',
          fillOpacity: 0.35,
        })
        
        map.value.add(binjiangqupolygon.value)
      }
    }
  })
}, 300)

// 轮渡切换
const toggleLundu = () => {
  showLundu.value = !showLundu.value
  if (showLundu.value) {
    if (!lundulineSpolyline.value) {
      lundulineSpolyline.value = initLundu()
    }
    lundulineSpolyline.value.show()
  } else if (lundulineSpolyline.value) {
    lundulineSpolyline.value.hide()
  }
}

// 地铁线路管理
const initSubway = async (name) => {
  if (!lineSearch.value || !map.value) return

  return new Promise((resolve) => {
    lineSearch.value.search(name, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        const lines = []
        if (result.lineInfo && result.lineInfo.length > 0) {
          result.lineInfo.forEach((lineInfo) => {
            if (lineInfo.path && lineInfo.path.length > 0) {
              const polyline = createPolyline(lineInfo.path, name)
              if (polyline) {
                lines.push(polyline)
                polyline.hide() // 默认隐藏
              }
            }
          })
        }
        subwayLinesMap.value.set(name, lines)
        resolve(lines)
      } else {
        resolve([])
      }
    })
  })
}

const toggleSubwayList = debounce(async (names = LINES) => {
  showSubway.value = !showSubway.value
  
  for (const name of names) {
    await toggleSubway(name)
  }
}, 200)

const toggleSubway = async (name) => {
  let lines = subwayLinesMap.value.get(name)
  
  if (!lines || lines.length === 0) {
    lines = await initSubway(name)
  }
  
  if (lines && lines.length > 0) {
    lines.forEach(polyline => {
      if (showSubway.value) {
        polyline.show()
      } else {
        polyline.hide()
      }
    })
  }
}

// 公交线路管理
const initBus = async (name) => {
  if (!lineSearch.value || !map.value) return

  return new Promise((resolve) => {
    lineSearch.value.search(name, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        const lines = []
        if (result.lineInfo && result.lineInfo.length > 0) {
          result.lineInfo.forEach((lineInfo) => {
            if (lineInfo.path && lineInfo.path.length > 0) {
              const polyline = createPolyline(lineInfo.path, name)
              if (polyline) {
                lines.push(polyline)
                polyline.hide()
              }
            }
          })
        }
        busLinesMap.value.set(name, lines)
        resolve(lines)
      } else {
        resolve([])
      }
    })
  })
}

const toggleBusList = debounce(async (names = BUS_LINES) => {
  showBus.value = !showBus.value
  
  for (const name of names) {
    await toggleBus(name)
  }
}, 200)

const toggleBus = async (name) => {
  let lines = busLinesMap.value.get(name)
  
  if (!lines || lines.length === 0) {
    lines = await initBus(name)
  }
  
  if (lines && lines.length > 0) {
    lines.forEach(polyline => {
      if (showBus.value) {
        polyline.show()
      } else {
        polyline.hide()
      }
    })
  }
}

// 标记点管理
const markersShow = () => {
  isShowMarkers.value = !isShowMarkers.value
  if (isShowMarkers.value) {
    addMarkers()
  } else {
    clearMarkers()
  }
}

const addMarkers = () => {
  const AMapInstance = window.AMap
  if (!AMapInstance || !map.value || !props.markers.length) return

  clearMarkers()

  const markers = props.markers.map(markerData => {
    const marker = new AMapInstance.Marker({
      position: markerData.position,
      title: markerData.title,
      content: createMarkerContent(markerData),
      offset: new AMapInstance.Pixel(-13, -30),
    })

    marker.on('click', () => {
      sendMessageToCSharp({
        type: 'marker',
        id: markerData.id,
        name: markerData.title,
        position: markerData.position,
      })
    })

    return marker
  })

  map.value.add(markers)
  markerInstances.value = markers
}

const createMarkerContent = (markerData) => {
  if (markerData.useIconImage) {
    return `<div class="icon-image-marker" style="width:81px;height:97px;position:relative;display:flex;justify-content:center">
      <img src="${markerData.bgIconImage}" alt="${markerData.title}" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 1;">
      <img src="${markerData.iconImage}" alt="${markerData.title}" style="width: 40px;height:40px;margin-top:23px; position: relative; z-index: 2;">
    </div>`
  }

  return `<div style="
    background: #ff4444;
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    white-space: nowrap;
  ">${markerData.title}</div>`
}

const clearMarkers = () => {
  if (map.value && markerInstances.value.length) {
    map.value.remove(markerInstances.value)
    markerInstances.value = []
  }
}

// 区域显示
const showDistrictNames = () => {
  const AMap = window.AMap
  if (!AMap || !map.value) return

  clearDistrictMarkers()

  const districts = [
    { name: '上城区', position: [120.16, 30.25], radius: 800 },
    { name: '下城区', position: [120.15, 30.28], radius: 700 },
    { name: '江干区', position: [120.2, 30.27], radius: 1000 },
    { name: '拱墅区', position: [120.13, 30.3], radius: 900 },
    { name: '西湖区', position: [120.08, 30.25], radius: 1200 },
    { name: '滨江区', position: [120.2, 30.2], radius: 1900 },
    { name: '萧山区', position: [120.27, 30.17], radius: 1500 },
    { name: '余杭区', position: [120.3, 30.25], radius: 1800 },
    { name: '临安区', position: [120.3, 30.35], radius: 2000 },
  ]

  const markers = districts.flatMap(district => {
    const marker = new AMap.Marker({
      position: district.position,
      title: district.name,
      content: `<div style="
        color: #fff;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: bold;
        white-space: nowrap;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        border-radius: 16px;
      ">${district.name}</div>`,
      offset: new AMap.Pixel(-30, -15),
      clickable: true,
    })

    if (district.name === '滨江区') {
      marker.on('click', () => {
        toggleBusList()
        toggleSubwayList()
        toggleLundu()
        clearDistrictMarkers()
        searchAndDrawBinjiangBoundary()
      })
    }

    const circle = new AMap.Circle({
      center: district.position,
      radius: district.radius,
      fillColor: 'rgba(255, 255, 0, 0.2)',
      fillOpacity: 0.2,
      strokeColor: 'rgba(255, 255, 0, 0.4)',
      strokeOpacity: 0.4,
      strokeWeight: 1,
    })

    return [marker, circle]
  })

  map.value.add(markers)
  districtMarkers.value = markers
}

const clearDistrictMarkers = () => {
  if (map.value && districtMarkers.value.length > 0) {
    map.value.remove(districtMarkers.value)
    districtMarkers.value = []
  }
}

const toggleDistricts = () => {
  showDistricts.value = !showDistricts.value
  if (showDistricts.value) {
    showDistrictNames()
  } else {
    clearDistrictMarkers()
  }
}

// 基础控制方法
const zoomIn = () => map.value?.zoomIn()
const zoomOut = () => map.value?.zoomOut()
const centerMap = () => {
  if (map.value) {
    map.value.setCenter(props.center)
    map.value.setZoom(props.zoom)
  }
}

const toggleSatellite = () => {
  if (map.value && satelliteLayer.value) {
    isSatellite.value = !isSatellite.value
    if (isSatellite.value) {
      satelliteLayer.value.show()
    } else {
      satelliteLayer.value.hide()
    }
  }
}

// 热力图
const toggleHeatmap = debounce(() => {
  showHeatmap.value = !showHeatmap.value
  if (heatmap.value) {
    if (showHeatmap.value) {
      // 简化热力图数据，减少点数
      const heatDataEffect = {
        max: 20,
        data: [
          // 只保留关键区域的热力图数据点，减少数据量
          { lng: 120.153576, lat: 30.159326, count: 10 },
          { lng: 120.148952, lat: 30.162456, count: 8 },
          { lng: 120.157891, lat: 30.166789, count: 15 },
          { lng: 120.168945, lat: 30.172345, count: 20 },
          { lng: 120.172345, lat: 30.238765, count: 9 },
          { lng: 120.198765, lat: 30.252345, count: 22 },
        ],
      }
      heatmap.value.setDataSet(heatDataEffect)
      heatmap.value.show()
    } else {
      heatmap.value.hide()
    }
  }
}, 300)

// 路线
const toggleRoute = debounce((ls = [
  [120.190826, 30.194148],
  [120.186623, 30.16643],
  [120.1685231311056, 30.161578213867102],
]) => {
  showToggle.value = !showToggle.value
  if (showToggle.value) {
    if (!myLine.value) {
      myLine.value = createPolyline(ls, '自定义路线', { strokeColor: '#E67818' })
    }
    myLine.value.show()
  } else if (myLine.value) {
    myLine.value.hide()
  }
}, 300)

// C# 通信
const sendMessageToCSharp = (data) => {
  if (window.vuplex) {
    sendMessage(data)
  } else {
    window.addEventListener('vuplexready', sendMessage)
  }
}

const sendMessage = ({ type, ...data }) => {
  window.vuplex.postMessage({ type, ...data })
}

// 清理资源
const cleanup = () => {
  // 清理所有覆盖物
  clearMarkers()
  clearDistrictMarkers()
  
  // 清理线路
  subwayLinesMap.value.forEach(lines => {
    lines.forEach(line => map.value?.remove(line))
  })
  busLinesMap.value.forEach(lines => {
    lines.forEach(line => map.value?.remove(line))
  })
  
  // 清理其他覆盖物
  if (myLine.value) map.value?.remove(myLine.value)
  if (lundulineSpolyline.value) map.value?.remove(lundulineSpolyline.value)
  if (binjiangqupolygon.value) map.value?.remove(binjiangqupolygon.value)
  
  // 销毁地图
  if (map.value) {
    map.value.destroy()
    map.value = null
  }
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initMap()
  })
})

onUnmounted(() => {
  cleanup()
  // 移除所有事件监听器
  Object.keys(window).forEach(key => {
    if (key.startsWith('amapEvent')) {
      window.removeEventListener(key, window[key])
    }
  })
})

// 全局事件监听 - 使用防抖
const debouncedZoomIn = debounce(zoomIn, 100)
const debouncedZoomOut = debounce(zoomOut, 100)

window.addEventListener('zoomIn', debouncedZoomIn)
window.addEventListener('zoomOut', debouncedZoomOut)
window.addEventListener('centerMap', debounce(centerMap, 100))
window.addEventListener('isShowSatellite', debounce(() => toggleSatellite(true), 100))
window.addEventListener('isHideSatellite', debounce(() => toggleSatellite(false), 100))
window.addEventListener('toggleHeatmap', toggleHeatmap)
window.addEventListener('toggleSubwayList', toggleSubwayList)
window.addEventListener('toggleBusList', toggleBusList)
window.addEventListener('toggleLundu', debounce(toggleLundu, 100))
window.addEventListener('markersShow', debounce(markersShow, 100))
window.addEventListener('toggleRoute', toggleRoute)
window.addEventListener('toggleDistricts', debounce(toggleDistricts, 100))
window.addEventListener('searchAndDrawBinjiangBoundary', searchAndDrawBinjiangBoundary)
</script>

<style scoped>
/* 样式保持不变，已经比较优化 */
::v-deep(.amap-logo),
::v-deep(.amap-copyright),
::v-deep(.amap-maptypecontrol) {
  opacity: 0;
}

.amap-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 500px;
  border: 1px solid #e0e0e0;
  box-sizing: border-box;
  border-radius: 8px;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 100%;
  min-height: 500px;
}

.map-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background: rgba(255, 255, 255, 0.95);
  padding: 12px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
}

.control-btn {
  width: 44px;
  height: 44px;
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.control-btn:hover {
  background: #f8f9fa;
  border-color: #007bff;
  transform: translateY(-2px);
}

.control-btn.active {
  background: #007bff;
  color: white;
  border-color: #0056b3;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  color: #dc3545;
  font-weight: 500;
}
</style>